//
//  MineInfoTableViewController.m
//  FNMenu
//
//  Created by 航汇聚科技 on 2018/9/11.
//  Copyright © 2018年 Yi Zhou. All rights reserved.
//

@import Photos;
#import "MineInfoTableViewController.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import <SVProgressHUD/SVProgressHUD.h>
#import "NSDictionary+Safety.h"
#import "NSArray+Safety.h"
#import "MineInfoTableViewCell.h"
#import "UpdateViewController.h"
#import "NetManager.h"
#import "User.h"
@interface MineInfoTableViewController ()<UIImagePickerControllerDelegate, UINavigationControllerDelegate>
@property (nonatomic, strong) NSArray *titleForRows;
@property (nonatomic, strong) UIImagePickerController *imagePicker;
@property (nonatomic, strong) MineInfoTableViewCell *potraitCell;
@end

@implementation MineInfoTableViewController

#pragma mark - lifeCycle
- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    self.titleForRows = @[@"头像"];
    self.tableView.tableFooterView = [UIView new];
}

#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.titleForRows.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
     MineInfoTableViewCell *cell;
    if (indexPath.row == 0) {
        cell = [tableView dequeueReusableCellWithIdentifier:@"minePortraitCell" forIndexPath:indexPath];
        NSString *avatarAddressStr = [self.userInfo safeObjectForKey:@"avatar"];
#if DEBUG
        avatarAddressStr = [avatarAddressStr stringByReplacingOccurrencesOfString:@"https" withString:@"http"];
#else
#endif
        [cell.portraitImgView sd_setImageWithURL:[NSURL URLWithString:avatarAddressStr] placeholderImage:[UIImage imageNamed:@""]];
        self.potraitCell = cell;
    } else {
        cell = [tableView dequeueReusableCellWithIdentifier:@"mineNameCell" forIndexPath:indexPath];
        cell.nameLabel.text = [self.userInfo safeObjectForKey:@"name"];
    }
    // Configure the cell...
    cell.titleLabel.text = [self.titleForRows safeObjectAtIndex:indexPath.row];
    
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
            dispatch_async(dispatch_get_main_queue(), ^{
                switch (status) {
                    case PHAuthorizationStatusAuthorized: //已获取权限
                    {
                        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
                        imagePickerController.delegate = self; //设置代理
                        imagePickerController.allowsEditing = YES;
                        imagePickerController.sourceType =  UIImagePickerControllerSourceTypePhotoLibrary;
                        [self presentViewController:imagePickerController animated:YES completion:nil];
                    }
                        break;
                    case PHAuthorizationStatusDenied: //用户已经明确否认了这一照片数据的应用程序访问
                    case PHAuthorizationStatusRestricted://此应用程序没有被授权访问的照片数据。可能是家长控制权限
                    {
                        NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
                        CFShow(CFBridgingRetain(infoDictionary));
                        // app名称
                        NSString *app_Name = [infoDictionary objectForKey:@"CFBundleDisplayName"];
                        [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"请在iPhone的'设置-隐私-照片'选项中，允许'%@'访问你的照片",app_Name]];
                    }
                        break;
                    default://其他。。。
                        break;
                        
                }
            });
        }];
    }
    if (indexPath.row == 1) {
        UpdateViewController *updateVC = [UpdateViewController updateVCFromStoryBoard];
        updateVC.type = UPDATETYPE_Name;
        [self presentViewController:updateVC animated:YES completion:nil];
    }
}
#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    [[NetManager defaultNetManager] uploadPhoto:image urlStr:@"home/users/editinfo" parameters:@{@"uid":[User userID]} constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([[responseObject safeObjectForKey:@"code"] integerValue] == 1) {
            [self.potraitCell.portraitImgView setImage:image];
            [picker dismissViewControllerAnimated:YES completion:^{}];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"上传图片：%@",error);
    }];
  
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:^{}];
}
#pragma mark - public
+ (instancetype)mineInfoVCFromStoryBoard {
    return [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"MineInfoVC"];
}
@end
